<template>
  <el-button type="primary" @click="addUser">新增用户</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>
  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="60" />
    <el-table-column property="loginAct" label="账号" width="120"/>
    <el-table-column property="name" label="姓名" width="100" />
    <el-table-column property="phone" label="手机" width="150" />
    <el-table-column property="email" label="邮箱" show-overflow-tooltip />
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
    <el-table-column label="操作"  show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination background
                 layout="prev, pager, next"
                 :page-size="pageSize"
                 @change="toPage"
                 @prev-click="toPage"
                 @next-click="toPage"
                 :total="pageTotal" />

  <!--新增用户的弹窗（对话框）-->
  <el-dialog v-model="userDialogVisible" :title="userQuery.loginAct?'编辑用户':'新增用户'" width="55%" center>

    <el-form ref="userRefForm" :model="userQuery" label-width="110px" :rules="userRules">

      <el-form-item label="账号" prop="loginAct">
        <el-input v-model="userQuery.loginAct" />
      </el-form-item>

      <el-form-item label="密码" v-if="userQuery.id > 0">
        <el-input type="password" v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="密码" prop="loginPwd" v-else>
        <el-input type="password" v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-select v-model="userQuery.accountNoExpired" placeholder="请选择" style="width: 100%;">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-select v-model="userQuery.credentialsNoExpired" placeholder="请选择" style="width: 100%;">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号未锁定" prop="accountNoLocked">
        <el-select v-model="userQuery.accountNoLocked" placeholder="请选择" style="width: 100%;">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否可用" prop="accountEnabled">
        <el-select v-model="userQuery.accountEnabled" placeholder="请选择" style="width: 100%;">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="userSubmit">提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "UserView",
  //注入reload函数。
  inject:['reload'],
  data(){
      return{
        //用户列表数据，初始值为空
        userList:[{}],
        //每页条数
        pageSize:0,
        //总条数
        pageTotal:0,
        //新增窗口是否显示
        userDialogVisible:false,
        //定义用户表单对象
        userQuery:{},
        //定义新增用户表单提交时的验证规则
        userRules : {
          loginAct : [
            { required: true, message: '登录账号不能为空', trigger: 'blur' },
            { min: 3, max: 32, message: '登录账号长度范围为3-32个字符', trigger: 'blur' }
          ],
          loginPwd : [
            { required: true, message: '登录密码不能为空', trigger: 'blur' },
            { min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur' }
          ],
          name : [
            { required: true, message: '姓名不能为空', trigger: 'blur' },
            { pattern : /^[\u4e00-\u9fa5]{0,}$/, message: '姓名必须是中文汉字', trigger: 'blur'}
          ],
          phone : [
            { required: true, message: '手机号码不能为空', trigger: 'blur' },
            { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'}
          ],
          email : [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { pattern : /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式有误', trigger: 'blur'}
          ],
          accountNoExpired : [
            { required: true, message: '请选择账号是否未过期', trigger: 'blur' },
          ],
          credentialsNoExpired : [
            { required: true, message: '请选择密码是否未过期', trigger: 'blur' },
          ],
          accountNoLocked : [
            { required: true, message: '请选择账号是否未未锁定', trigger: 'blur' },
          ],
          accountEnabled : [
            { required: true, message: '请选择账号是否可用', trigger: 'blur' },
          ]
        },
        //定义options数组
        options : [
          {label : '是', value : 1},
          {label : '否', value : 0}
        ],
        //选中的用户id
        userIdArray:[],
      }
  },
  mounted() {
    //页面渲染时，查询第一页
    this.getUserData(1);
  },
  methods:{
    //勾选或取消勾选时，触发该函数
    handleSelectionChange(val){
      //清空数组
      this.userIdArray = [];
      //遍历，获取用户id
      val.forEach(data => {
        this.userIdArray.push(data.id);
      })
    },

    //查询用户列表数据
    getUserData(pageNum){
      doGet("/api/users",{pageNum}).then(res => {
        if(res.data.code === 200) {
          this.userList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.pageTotal  = res.data.data.total;
        }
      })
    },

    //分页函数（参数是element-plus组件传过来的，默认是当前页）
    toPage(pageNum){
      this.getUserData(pageNum);
    },

    //用户详情
    view(id) {
      //跳转到指定页面
      this.$router.push("/dashboard/user/" + id);
    },

    //新增用户
    addUser(){
      this.userQuery = {};
      this.userDialogVisible=true;
    },
    //用户提交请求
    userSubmit(){
      let formData = new FormData();
      for(let field in this.userQuery) {
        formData.append(field,this.userQuery[field]);
      }

      //进行表单验证,成功才发送请求
      this.$refs.userRefForm.validate((isValid) => {
        if(isValid) {
          if(this.userQuery.id > 0) {
            //编辑用户
            doPut("/api/user",formData).then(resp => {
              if(resp.data.code === 200) {
                messageTip("编辑成功","success");
                //局部刷新页面
                this.reload();
              }else {
                messageTip("编辑失败","error");
              }
            })
          }else {
            //新增用户
            doPost("/api/user",formData).then(resp => {
              if(resp.data.code === 200) {
                messageTip("新增成功","success");
                //局部刷新页面
                this.reload();
              }else {
                messageTip("新增失败","error");
              }
            })
          }
        }
      })
    },

    //编辑用户
    edit(id) {
      //编辑用户的弹窗和新增用户共用同一个弹窗
      this.userDialogVisible = true;
      //查询出该id用户的详情
      this.loadUser(id);
    },

    //加载用户数据
    loadUser(id) {
      doGet("/api/user/" + id,{}).then(resp => {
        if(resp.data.code === 200) {
          this.userQuery = resp.data.data;
          this.userQuery.loginPwd = "";
        }
      })
    },

    //删除用户
    del(id) {
      messageConfirm("是否确定删除该用户？").then(()=>{
        doDelete("/api/user/" + id,{}).then(resp => {
          if(resp.data.code === 200) {
            messageTip("删除成功","success");
            //页面局部刷新
            this.reload();
          }else {
            messageTip("删除失败,原因：" + resp.data.msg,"error");
          }
        })
      }).catch(()=>{
        messageTip("取消删除","warning");
      })
    },

    //批量删除用户
    batchDel(){
      if(this.userIdArray.length <= 0) {
        messageTip("至少选中一条数据","warning");
        return;
      }
      //将数组转换成字符串 [1,3,5,7] ----> ids = "1,3,5,7"
      let ids = this.userIdArray.join(",");
      messageConfirm("是否确定删除这些用户？").then(()=>{
        doDelete("/api/user",{ids}).then(resp => {
          if(resp.data.code === 200) {
            messageTip("批量删除成功","success");
            //页面局部刷新
            this.reload();
          }else {
            messageTip("批量删除失败,原因：" + resp.data.msg,"error");
          }
        })
      }).catch(()=>{
        messageTip("取消批量删除","warning");
      })
    },
  },
}
</script>
<style scoped>
.el-table{
  margin-top:12px;
}
.el-pagination {
  margin-top:12px;
}
</style>
